package com.rs.util.http;

/**
 *@author:ShaZhengBo
 *@createTime:2016年9月3日上午11:55:27
 *@description:<p><span>http帮助类</span></p>
 *@version:1.0
 */
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.rs.util.http.model.HttpResult;
@Deprecated
public class HttpUtil {
	private static HttpURLConnection httpURLConnection;
	private static HttpUtil client = null;

	private HttpUtil() {
	}

	private static synchronized void synInit() {
		if (client == null) {
			client = new HttpUtil();
		}
	}

	public static HttpUtil getInstance() {
		if (client == null) {
			synInit();
		}

		return client;
	}

	/**
	 * GET请求
	 * 
	 * @param url
	 *            地址
	 * @param params
	 *            Map<String,String> 参数
	 * @return String
	 */
	public HttpResult doGet(String url, Map<String, String> params) {
		return doGet(url, "UTF-8", params);
	}

	/**
	 * GET 请求
	 * 
	 * @param url
	 *            地址
	 * @param encode
	 *            编码
	 * @param params
	 *            Map<String,String> Or null
	 * @return String
	 */
	public HttpResult doGet(String url, String encode, Map<String, String> params) {
		String paramStr = "";
		if (params != null) {
			Object in;
			Object br;
			for (Iterator<?> strResult = params.entrySet().iterator(); strResult
					.hasNext(); paramStr = paramStr + "&" + in + "=" + br) {
				Entry<?, ?> e = (Entry<?, ?>) strResult.next();
				in = e.getKey();
				br = e.getValue();
			}

			if (!paramStr.equals("")) {
				paramStr = paramStr.replaceFirst("&", "?");
				url = url + paramStr;
			}
		}

		String strResult1 = "doGetError";
		Integer ResCode = 0;
		try {
			System.out.println("请求地址是:" + url);
			URL e1 = new URL(url);
			httpURLConnection = (HttpURLConnection) e1.openConnection();
			httpURLConnection.setRequestMethod("GET");
			httpURLConnection.setReadTimeout(10000);
			httpURLConnection.setConnectTimeout(10000);
			httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			ResCode = httpURLConnection.getResponseCode();
			System.out.println(ResCode);
			if (ResCode == 200) {
				InputStream in1 = httpURLConnection.getInputStream();
				BufferedReader br1 = new BufferedReader(new InputStreamReader(in1, encode));
				StringBuffer strBuffer = new StringBuffer();

				String line;
				while ((line = br1.readLine()) != null) {
					strBuffer.append(line);
				}
				strResult1 = strBuffer.toString();
			} else {
				if (ResCode == 404)
					strResult1 = "Error Response:服务器无响应!";
				else if (ResCode == 500)
					strResult1 = "Error Response:内部服务器错误!";
				else
					strResult1 = "Error Response:未知错误!";

			}
		} catch (Exception var14) {
			var14.printStackTrace();
			strResult1 = "Error Response:" + var14.getMessage();
		} finally {
			if (httpURLConnection != null) {
				httpURLConnection.disconnect();
			}

		}

		return new HttpResult(ResCode, strResult1);
	}

	/**
	 * POST 请求
	 * 
	 * @param url
	 *            请求地址
	 * @param params
	 *            Map<String,String>
	 * @return String
	 */
	public HttpResult doPost(String url, Map<String, String> params) {
		return doPost(url, "UTF-8", params);
	}

	/**
	 * POST请求
	 * 
	 * @param url
	 *            请求地址
	 * @param encode
	 *            编码
	 * @param params
	 *            Map<String,String> Or null
	 * @return String
	 */
	public HttpResult doPost(String url, String encode, Map<String, String> params) {
		byte[] data = getRequestData(params, encode).toString().getBytes();
		URL durl = null;
		Integer responseCode = 0;
		String responseStr = null;
		try {
			durl = new URL(url);
			httpURLConnection = (HttpURLConnection) durl.openConnection();
			httpURLConnection.setConnectTimeout(5 * 1000);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
			OutputStream e = httpURLConnection.getOutputStream();
			e.write(data);
			responseCode = httpURLConnection.getResponseCode();

			if (responseCode == 200) {
				InputStream inptStream = httpURLConnection.getInputStream();
				responseStr = dealResponseResult(inptStream);
			} else {
				if (responseCode == 404)
					responseStr = "Error Response:服务器无响应!";
				else if (responseCode == 500)
					responseStr = "Error Response:内部服务器错误!";
				else
					responseStr = "Error Response:未知错误!";

			}

		} catch (Exception var9) {
			var9.printStackTrace();
			return null;
		}
		return new HttpResult(responseCode, responseStr);
	}

	@SuppressWarnings("rawtypes")
	public static StringBuffer getRequestData(Map<String, String> params, String encode) {
		StringBuffer stringBuffer = new StringBuffer();

		try {

			if (params != null) {
				Iterator e = params.entrySet().iterator();

				while (e.hasNext()) {
					Entry entry = (Entry) e.next();
					stringBuffer.append((String) entry.getKey()).append("=")
							.append(URLEncoder.encode((String) entry.getValue(), encode)).append("&");
				}

				stringBuffer.deleteCharAt(stringBuffer.length() - 1);
			}
		} catch (Exception var5) {
			var5.printStackTrace();
		}

		return stringBuffer;
	}

	public static String dealResponseResult(InputStream inputStream) {
		String resultData = null;
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		@SuppressWarnings("unused")
		boolean len = false;

		int len1;
		try {
			while ((len1 = inputStream.read(data)) != -1) {
				byteArrayOutputStream.write(data, 0, len1);
			}
		} catch (IOException var6) {
			var6.printStackTrace();
		}

		resultData = new String(byteArrayOutputStream.toByteArray());
		return resultData.toString();
	}

	/**
	 * RESTFUL 风格请求
	 * 
	 * @param url
	 *            请求地址
	 * @param params
	 *            String[] Or null
	 * @return String
	 */
	public HttpResult doRestful(String url, String... params) {
		return doRestful(url, "UTF-8", params);
	}

	/**
	 * RestFul风格请求
	 * 
	 * @param url
	 *            请求地址
	 * @param encode
	 *            编码格式
	 * @param params
	 *            String[] Or Don't write
	 * @return String
	 */
	public HttpResult doRestful(String url, String encode, String... params) {
		String paramStr = "";
		if (params != null) {
			if (!url.endsWith("/"))
				paramStr = paramStr + "/";

			for (String param : params) {
				paramStr = paramStr + param + "/";
			}

			if (!paramStr.equals("/")) {
				url = url + paramStr;
			}
		}
		Integer resCode = 0;
		String responseStr = "doRestFulError";
		try {
			URL e1 = new URL(url);
			httpURLConnection = (HttpURLConnection) e1.openConnection();
			httpURLConnection.setRequestMethod("GET");
			httpURLConnection.setReadTimeout(10000);
			httpURLConnection.setConnectTimeout(10000);
			httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			resCode = httpURLConnection.getResponseCode();
			if (resCode == 200) {
				InputStream in1 = httpURLConnection.getInputStream();
				BufferedReader br1 = new BufferedReader(new InputStreamReader(in1, encode));
				StringBuffer strBuffer = new StringBuffer();

				String line;
				while ((line = br1.readLine()) != null) {
					strBuffer.append(line);
				}
				responseStr = strBuffer.toString();
			} else {
				if (resCode == 404)
					responseStr = "Error Response:服务器无响应!";
				else if (resCode == 500)
					responseStr = "Error Response:内部服务器错误!";
				else
					responseStr = "Error Response:未知错误!";

			}
		} catch (Exception var14) {
			var14.printStackTrace();
			responseStr = "Error Response:" + var14.getMessage();
		} finally {
			if (httpURLConnection != null) {
				httpURLConnection.disconnect();
			}

		}

		return new HttpResult(resCode, responseStr);
	}
}
